﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.IO;
using System.Net.Security;
using System.Security.Authentication;
using System.Threading;
using System.Security.Cryptography.X509Certificates;
using System.Xml.Linq;
using System.Diagnostics;

namespace AllTalkProxy
{
    class Program
    {
        static void Main(string[] args)
        {
            if (Debugger.IsAttached)
            {
                Constants.BindTimeout = 99999;
            }

            ConnectionManager connectionManager = new ConnectionManager(
                ServerConfiguration.ChatServer,
                ServerConfiguration.Port,
                UserConfiguration.Username,
                UserConfiguration.Password);
            Jid result = connectionManager.Connect();
            string roosterXml;
            connectionManager.GetRooster(out roosterXml);
            connectionManager.GetVCard("nikhil.khandelwal@gmail.com");
            Thread.Sleep(300);
            connectionManager.Dispose();
            Console.Read();
        }

        

       

     

     



        private static string ReadHeaderResponse(Stream stream, string expectedToken)
        {
            string response1 = ReadAll(stream);
            Log(response1, "First response");

            if (!response1.Contains(expectedToken))
            {
                string response2 = ReadAll(stream);
                Log(response2, "Second response");
                response1 += response2;
            }
            return response1;
        }

        private static string ReadAll(Stream stream, string endingToken = "")
        {
            byte[] buffer = new byte[4096];
            StringBuilder sb = new StringBuilder();
            int charsRead;
            string currentChunk;
            do
            {
                charsRead = stream.Read(buffer, 0, buffer.Length);
                currentChunk = Encoding.UTF8.GetString(buffer, 0, charsRead);
                sb.Append(currentChunk);

                if (!String.IsNullOrEmpty(endingToken) && !currentChunk.EndsWith(endingToken))
                {
                    continue;
                }
                if (charsRead < buffer.Length)
                    break;
            } while (charsRead > 0);

            return sb.ToString();
        }


        private static void Log(string message, string title = "")
        {
            Console.WriteLine(title);
            Console.WriteLine(message);
            Console.WriteLine();
        }
    }
}
